package com.zh.ssmshirofreemarker.websocket;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket",configurator = GetHttpSessionConfigurator.class)
@Component
public class WebSocketTest {

    //静态变量，用来记录当前在线连接数。应该把它设为线程安全的
    private static int onlineCount = 0;

    //concurrent 包的线程安全set，用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话，可以
    //使用Map 来存放，其中key可以为用户标志
    private static Map<String,WebSocketTest> webSocketMap = new ConcurrentHashMap<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    /**
     * 连接建立成功后调用的方法
     *
     */
    @OnOpen
    public void onOpen(Session session,EndpointConfig config){

        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
       this.session = session;

       webSocketMap.put(httpSession.getAttribute("username").toString(),this);
        System.out.println(httpSession.getAttribute("username"));
       addOnlineCount();
       System.out.println("有一个连接加入！当前在线人数为" + getOnlineCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketMap.remove("zh");
        subOnlineCount();
        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        System.out.println("来自客户端发送的消息：" + message);
        //群发消息
        for(Map.Entry<String,WebSocketTest> map:webSocketMap.entrySet()){
              try{
                   map.getValue().sendMessage(message);
              } catch (IOException e){
                  e.printStackTrace();
                  continue;
              }
        }
    }

    @OnError
    public void onError(Session session,Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public static synchronized int getOnlineCount(){
        return onlineCount;
    }

    public static synchronized void addOnlineCount(){
        WebSocketTest.onlineCount++;
    }

    public static synchronized void subOnlineCount(){
        WebSocketTest.onlineCount--;
    }

    public static void sendMessage(String msg,String username) throws IOException, EncodeException {
        WebSocketTest webSocketTest = webSocketMap.get(username);
        if(webSocketTest != null){
            webSocketTest.session.getBasicRemote().sendText(msg);
        }
    }

}
